<script setup lang="ts">
import { computed, onActivated, onMounted, ref } from 'vue';
import { fetchUserGames } from '@/service/api/game';
import { useAuthStore } from '@/store/modules/auth';
import { fetchCategories, fetchGameList, fetchHotGames, fetchNewGames, fetchRecommendGames } from './modules/api';
import Sidebar from './modules/sidebar.vue';
import Banner from './modules/banner.vue';
import GameList from './modules/game-list.vue';
import SearchBar from './modules/search-bar.vue';
import CategoryBar from './modules/category-bar.vue';

const allGames = ref([]); // 存储所有游戏数据
const games = ref([]); // 显示的游戏数据
const categories = ref([]);
const recommendGames = ref([]);
const hotGames = ref([]);
const newGames = ref([]);
const banners = ref([{ img: '/banner/slide1.png' }, { img: '/banner/slide2.png' }, { img: '/banner/slide3.png' }]);

const searchKeyword = ref('');
const selectedCategory = ref('');
const ownedGameIds = ref<number[]>([]);
const authStore = useAuthStore();

// 加载所有数据
async function loadAll() {
  await Promise.all([loadGameList(), loadCategories(), loadRecommendGames(), loadHotGames(), loadNewGames()]);
}

async function loadGameList() {
  try {
    const res = await fetchGameList({ pageNum: 1, pageSize: 100 }); // 获取更多数据用于前端筛选
    allGames.value = res.data || [];
    filterGames();
  } catch (error) {
    console.error('加载游戏列表失败:', error);
    allGames.value = [];
    games.value = [];
  }
}

async function loadCategories() {
  try {
    const res = await fetchCategories();
    // 从分组数据中提取分类名称
    if (res.data && Array.isArray(res.data)) {
      const categorySet = new Set();
      res.data.forEach((game: any) => {
        if (game.category) {
          categorySet.add(game.category);
        }
      });
      categories.value = Array.from(categorySet);
    } else {
      categories.value = [];
    }
  } catch (error) {
    console.error('加载分类失败:', error);
    categories.value = [];
  }
}

async function loadRecommendGames() {
  try {
    const res = await fetchRecommendGames();
    recommendGames.value = res.data || [];
  } catch (error) {
    console.error('加载推荐游戏失败:', error);
    recommendGames.value = [];
  }
}

async function loadHotGames() {
  try {
    const res = await fetchHotGames();
    hotGames.value = res.data || [];
  } catch (error) {
    console.error('加载热门游戏失败:', error);
    hotGames.value = [];
  }
}

async function loadNewGames() {
  try {
    const res = await fetchNewGames();
    newGames.value = res.data || [];
  } catch (error) {
    console.error('加载最新游戏失败:', error);
    newGames.value = [];
  }
}

async function loadUserGames() {
  const userId = authStore.userInfo.userId;
  if (userId) {
    try {
      const res = await fetchUserGames(userId);
      const list = Array.isArray(res) ? res : (res?.data ?? []);
      ownedGameIds.value = list.map((g: any) => g.gameId || g.id);
    } catch {
      ownedGameIds.value = [];
    }
  }
}

// 前端筛选游戏
function filterGames() {
  let filteredGames = [...allGames.value];

  // 按分类筛选
  if (selectedCategory.value) {
    filteredGames = filteredGames.filter(
      game => game.category && game.category.toLowerCase() === selectedCategory.value.toLowerCase()
    );
  }

  // 按关键词搜索（不区分大小写）
  if (searchKeyword.value && searchKeyword.value.trim()) {
    const keyword = searchKeyword.value.toLowerCase().trim();
    filteredGames = filteredGames.filter(
      game =>
        (game.gameName && game.gameName.toLowerCase().includes(keyword)) ||
        (game.description && game.description.toLowerCase().includes(keyword)) ||
        (game.category && game.category.toLowerCase().includes(keyword))
    );
  }

  games.value = filteredGames;
}

onMounted(async () => {
  await loadAll();
  await loadUserGames();
});
onActivated(loadAll);

function handleSearch(keyword: string) {
  searchKeyword.value = keyword;
  filterGames();
}

function handleCategoryChange(category: string) {
  selectedCategory.value = category;
  filterGames();
}

function handlePageChange(pageNum: number) {
  // 分页逻辑可以在这里实现
}
</script>

<template>
  <div class="mall-home">
    <Sidebar :recommend-games="recommendGames" :hot-games="hotGames" :new-games="newGames" />
    <div class="mall-content">
      <SearchBar @search="handleSearch" />
      <Banner :banners="banners" />
      <CategoryBar :categories="categories" @change="handleCategoryChange" />
      <GameList :games="games" :owned-game-ids="ownedGameIds" />
      <!-- 可加分页组件，@change="handlePageChange" -->
    </div>
  </div>
</template>

<style scoped>
.mall-home {
  display: flex;
  background: #f5f6fa;
  min-height: 100vh;
}
.mall-content {
  flex: 1;
  padding: 24px;
  background: #f5f6fa;
}
</style>
